package com.vcredit.creditcat.service.product.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.springframework.util.ReflectionUtils;

public class EnumExtUtil {
	/**
	 * 由枚举属性值获取它本身 <code>
	 *  AuthMarriageEnum enumOnValue =  EnumUtil.getEnumOnValue(AuthMarriageEnum.class, String.valueOf("1"), "code");
	 *  AuthMarriageEnum enumyihun =  EnumUtil.getEnumOnValue(AuthMarriageEnum.class, String.valueOf("已婚"), "desc");
	 * System.out.println(enumOnValue);
	 * System.out.println(enumyihun);
	 * </code>
	 * 
	 * @param enumType
	 * @param value
	 * @param field
	 * @return
	 * @throws Exception
	 * @author 张新功
	 */
	@SuppressWarnings("unchecked")
	public static <T extends Enum<T>> T getEnumOnValue(Class<T> enumType, String value, String field) throws Exception {

		for (Object obj : enumType.getEnumConstants()) {
			Method m = obj.getClass().getDeclaredMethod("values", null);
			Object[] results = (Object[]) m.invoke(obj, null);
			for (Object result : results) {
				Field codeField = result.getClass().getDeclaredField(field);
				ReflectionUtils.makeAccessible(codeField);
				String fileValue = String.valueOf(ReflectionUtils.getField(codeField, result));
				if (fileValue.equals(value)) {
					return (T) result;
				}

			}
		}
		return null;
	}
}
